package qdu.rg012.clt_srv_msgr;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class Srv1 extends Service {

    class MyHandler extends Handler{
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch(msg.what){
                case 13:
                    Bundle bd = msg.getData();
                    Log.i("mytag","msg from client:" + bd.getString("cltmsg"));

                    //-------------准备发往客户端的message对象-----------------
                    Message srv_msg = Message.obtain();
                    srv_msg.what = 17;
                    Bundle srvbd = new Bundle();
                    srvbd.putString("srvmsg","hello client~");
                    srv_msg.setData(srvbd);
                    //-----------发送消息对象------------------
                    try {
                        msg.replyTo.send(srv_msg);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    } catch(Exception e){}
                    break;
            }
        }
    }
    Messenger msgr_srv;
    @Override
    public void onCreate() {
        super.onCreate();
        msgr_srv = new Messenger(new MyHandler());
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return msgr_srv.getBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {

        return super.onUnbind(intent);
    }
}
